package com.youdianda.service.impl;


import com.youdianda.constant.MessageConstant;
import com.youdianda.constant.StatusConstant;
import com.youdianda.context.BaseContext;
import com.youdianda.dto.AdminLoginDTO;
import com.youdianda.dto.ProfileDictList;
import com.youdianda.dto.ProfileUserInfo;
import com.youdianda.dto.User;
import com.youdianda.entity.*;
import com.youdianda.exception.PasswordErrorException;
import com.youdianda.mapper.*;
import com.youdianda.service.IndexService;
import com.youdianda.vo.BaseInfoVO;
import com.youdianda.vo.GetConfigVO;
import com.youdianda.vo.ProfileVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private YddCateMapper yddCateMapper;
    @Autowired
    private YddAdvposMapper yddAdvposMapper;
    @Autowired
    private YddTagMapper yddTagMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private YddArticleMapper yddArticleMapper;
    @Autowired
    private YddAdvimgMapper yddAdvimgMapper;
    @Autowired
    private YddUserMapper yddUserMapper;
    @Autowired
    private YddUserDataMapper yddUserDataMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysDictMapper sysDictMapper;



    /**
     * GET 管理获取系统配置
     *
     * @return
     */
    @Override
    public GetConfigVO getConfig() {
        String tabValue="system";
        List<SysConfig> sysConfigs = sysConfigMapper.getConfig(tabValue);
        GetConfigVO getConfigVO=new GetConfigVO();
        for (SysConfig config : sysConfigs) {
            String attrKey=config.getAttrKey();
            switch (attrKey){
                case "login_title":
                    getConfigVO.setLoginTitle(config.getAttrValue());
                    break;
                case "login_bg":
                    getConfigVO.setLoginBg(config.getAttrValue());
                    break;
                case "system_name":
                    getConfigVO.setSystemName(config.getAttrValue());
                    break;
                case "system_logo":
                    getConfigVO.setSystemLogo(config.getAttrValue());
                    break;
                case "webIco":
                    getConfigVO.setWebIco(config.getAttrValue());
                    break;
            }
        }
        return getConfigVO;
    }

    /**
     * 主页统计信息
     *
     * @return
     */
    @Override
    public BaseInfoVO baseInfo() {
        //所有分类数据
        List<YddCate> allCate = yddCateMapper.getAll();
        //广告总位数
        Integer advposNum = yddAdvposMapper.getNumber();
        //标签总数
        Integer tagNum = yddTagMapper.getNumber();
        //管理员总数
        Integer adminNum = sysUserMapper.getNumber();
        //文章总数
        Integer articleNum = yddArticleMapper.getNumber();
        //分类总数
        Integer cateNum = yddCateMapper.getNumber();
        //广告图总数
        Integer advimgNum = yddAdvimgMapper.getNumber();
        //最新用户数据
        List<YddUser> newUser = yddUserMapper.getAll();
        //热门文章数据
        List<YddArticle> hotArticle = yddArticleMapper.getHot();
        //用户数据
        User user = yddUserMapper.getUser();

        return BaseInfoVO.builder()
                .allCate(allCate)
                .advposNum(advposNum)
                .tagNum(tagNum)
                .adminNum(adminNum)
                .articleNum(articleNum)
                .cateNum(cateNum)
                .advimgNum(advimgNum)
                .newUser(newUser)
                .hotArticle(hotArticle)
                .user(user)
                .build();
    }

    /**
     * 后台登录接口
     *
     * @param adminLoginDTO
     */
    @Override
    public SysUser login(AdminLoginDTO adminLoginDTO) throws AccountNotFoundException, AccountLockedException {

        String loginName = adminLoginDTO.getLoginName();
        String password = adminLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        SysUser sysUser = sysUserMapper.login(loginName);


        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (sysUser == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(sysUser.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (sysUser.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return sysUser;
    }

    /**
     * 获取用户资料
     *
     * @return
     */
    @Override
    public ProfileVO profile() {
        Long sysUserId = BaseContext.getCurrentId();
        //用户资料
        SysUser sysUser = sysUserMapper.getById(sysUserId);
        String s = sysUser.getRoleId();
        String roleId = s.substring(2, s.length() - 2);
        //用户资料-角色名称
        SysRole sysRole = sysRoleMapper.getById(roleId);
        ProfileUserInfo profileUserInfo = new ProfileUserInfo();
        BeanUtils.copyProperties(sysUser, profileUserInfo);
        profileUserInfo.setRoleName(sysRole.getName());
        //用户菜单权限
        List<SysMenu> List = sysMenuMapper.getByRoleId(roleId);
        List<SysMenu> menuList=new ArrayList<>();
        //按钮List<String> btnList;
        List<String> btnList=new ArrayList<>();
        //TODO 暂且这样写吧 新的内容
        btnList.add("*");
        //TODO
        for (SysMenu sysMenu : List) {
            Integer type=sysMenu.getType();
           /* if(type==2){
                //如果类型是2 则是按钮
                btnList.add(String.valueOf(type));
            }else */if(type==1){
                //如果类型是1 则是菜单
                menuList.add(sysMenu);
            }
        }
        //dictsList
        ProfileDictList profileDictList = new ProfileDictList();
        //找到所有的type
        List<String> types = sysDictMapper.getType();
        //遍历type
        for (String type : types) {
            //拿到每个type的value
            List<String> typeValue = sysDictMapper.getTypeValue(type);
            Map<String,String> map=new HashMap<>();
            for (String value : typeValue) {
                map.put(value,value);
            }
            switch (type) {
                case "interface_type":
                    profileDictList.setInterfaceType(map);
                    break;
                case "order_type":
                    profileDictList.setOrderType(map);
                    break;
                case "report_type":
                    profileDictList.setReportType(map);
                    break;
                case "table_type":
                    profileDictList.setTableType(map);
                    break;
                case "theme":
                    profileDictList.setThem(map);
                    break;
            }
        }
        ProfileVO profileVO = ProfileVO.builder()
                .userInfo(profileUserInfo)
                .menuList(menuList)
                .dictsList(profileDictList)
                .btnList(btnList)
                .build();
        return profileVO;
    }

}
